package com.buka.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.buka.api.CouponApi;
import com.buka.api.StockApi;
import com.buka.common.BizCodeEnum;
import com.buka.dao.ProductOrderDao;
import com.buka.dto.ConfirmOrderDto;
import com.buka.entity.ProductOrder;
import com.buka.exception.BizException;
import com.buka.interceptor.LoginUserInterceptor;
import com.buka.request.LockCouponRequest;
import com.buka.request.LockProductRequest;
import com.buka.request.OrderItemRequest;
import com.buka.service.ProductOrderService;
import com.buka.util.CommonUtil;
import com.buka.util.JsonData;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * (ProductOrder)表服务实现类
 *
 * @author makejava
 * @since 2025-08-12 14:27:52
 */
@Service("productOrderService")
public class ProductOrderServiceImpl extends ServiceImpl<ProductOrderDao, ProductOrder> implements ProductOrderService {

    @Resource
    StockApi stockApi;

    @Resource
    CouponApi couponApi;

    /***
     *
     * 防重提交:是不是重复提交
     * 用户微服务-确认收货地址 *
     * 商品微服务-获取最新购物项和价格 *
     * 订单验价
     * 优惠券微服务-获取优惠券  *
     * 验证价格
     * 锁定优惠券  *
     * 锁定商品库存  *
     * 创建订单对象
     * 创建子订单对象
     * 发送延迟消息-用于自动关单
     * 创建支付信息-对接三方支付
     */
    @Override
    @GlobalTransactional
    public JsonData confirm(ConfirmOrderDto confirmOrderDto) {

        List<OrderItemRequest> productIdList = confirmOrderDto.getProductList();
        String outTradeNo = createOutTradeNo();

        //锁定库存
//        lockStock(outTradeNo, productIdList);
        //锁定优惠券领取记录的ID
        Long userId = LoginUserInterceptor.threadLocal.get().getId();
        lockCoupon(outTradeNo, confirmOrderDto.getCouponRecordIdList(),userId);

        //发起支付
        //支付页面

        return JsonData.buildSuccess();
    }

    private void lockCoupon(String outTradeNo, List<Long> couponRecordIdList,Long userId) {

        //发起优惠券服务调用 锁定优惠券

        LockCouponRequest lockCouponRequest = new LockCouponRequest();
        lockCouponRequest.setUserId(userId);
        lockCouponRequest.setOutTradeNo(outTradeNo);
        lockCouponRequest.setCouponRecordIdList(couponRecordIdList);

        JsonData jsonData = couponApi.lockCoupon(lockCouponRequest);
        if(jsonData.getCode() != 0){ //调用失败
            log.error("锁定优惠券失败！");
            new BizException(BizCodeEnum.LOCK_COUPON_ERROR);
        }
    }

    @Override
    public JsonData queryOrderState(String outTradeNo) {
        LambdaQueryWrapper<ProductOrder> orderQuery = Wrappers.lambdaQuery(ProductOrder.class);
        orderQuery.eq(ProductOrder::getOutTradeNo, outTradeNo);
        ProductOrder one = getOne(orderQuery);
        if (null != one) {//订单存在，返回订单状态
            return JsonData.buildSuccess(one.getState());
        } else {
            //订单不存在,返回异常信息
            return JsonData.buildResult(BizCodeEnum.NO_ORDER);
        }
    }

    private String createOutTradeNo() {
        //订单编号 日期+随机数
        String randomCode = CommonUtil.getRandomCode(4);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String dateStr = sdf.format(new Date());
        return dateStr + randomCode;
    }

    private void lockStock(String outTradeNo, List<OrderItemRequest> productList) {

        //扣减库存远程调用
        LockProductRequest lockProductRequest = new LockProductRequest();

        lockProductRequest.setOrderOutTradeNo(outTradeNo);
        lockProductRequest.setOrderItemRequest(productList);

        JsonData reduce = stockApi.reduce(lockProductRequest);
        if(reduce.getCode() != 0){
            log.error("扣减库存失败！");
            throw new RuntimeException(reduce.getMsg());
        }

    }
}

